﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;

namespace Cotrobaie.WebServicies
{
    /// <summary>
    /// Summary description for Ajax
    /// </summary>
    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [System.ComponentModel.ToolboxItem(false)]
    // To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line. 
    [System.Web.Script.Services.ScriptService]
    public class Ajax : System.Web.Services.WebService
    {

        #region Search dinamic Users
        [WebMethod]
        public string[] GetNormalUsersStrings(string prefixText, int count)
        {
            prefixText = prefixText.ToLower();
            List<string> rez = new List<string>(count);
            using (var dbs = new DB.DBCotrobaie())
            {
                Func<DB.Useri, bool> fct = (DB.Useri u) => (u.Username + " <" + u.E_mail + "> ").ToLower().Substring(0, prefixText.Length) == prefixText && u.AccountIsValidated && !u.AccountIsSuspended && !u.AccountIsTempDeleted;
                var UserMatch = dbs.Useri.Where(fct).Select(o => new { UsernameEmail = o.Username + " <" + o.E_mail + "> " });

                Func<DB.Useri, bool> fct2 = (DB.Useri u) => (u.Username + " <" + u.E_mail + "> ").ToLower().Contains(prefixText) && u.AccountIsValidated && !u.AccountIsSuspended && !u.AccountIsTempDeleted;
                var User = dbs.Useri.Where(fct2).Select(o => new { UsernameEmail = o.Username + " <" + o.E_mail + "> " });

                foreach (var u in UserMatch.Concat(User))
                    if (rez.Count < count) rez.Add(u.UsernameEmail);
                    else break;
            }
            if (rez.Count > 0) return rez.Distinct().ToArray();
            else { rez = new List<string>(1); rez.Add(" - "); }

            return rez.ToArray<string>();
        }
        [WebMethod]
        public string[] GetSuspendedUsersStrings(string prefixText, int count)
        {
            prefixText = prefixText.ToLower();
            List<string> rez = new List<string>(count);
            using (var dbs = new DB.DBCotrobaie())
            {
                Func<DB.Useri, bool> fct = (DB.Useri u) => (u.Username + " <" + u.E_mail + "> ").ToLower().Substring(0, prefixText.Length) == prefixText && u.AccountIsValidated && u.AccountIsSuspended && !u.AccountIsTempDeleted;
                var UserMatch = dbs.Useri.Where(fct).Select(o => new { UsernameEmail = o.Username + " <" + o.E_mail + "> " });

                Func<DB.Useri, bool> fct2 = (DB.Useri u) => (u.Username + " <" + u.E_mail + "> ").ToLower().Contains(prefixText) && u.AccountIsValidated && !u.AccountIsSuspended && u.AccountIsTempDeleted;
                var User = dbs.Useri.Where(fct2).Select(o => new { UsernameEmail = o.Username + " <" + o.E_mail + "> " });

                foreach (var u in UserMatch.Concat(User))
                    if (rez.Count < count) rez.Add(u.UsernameEmail);
                    else break;
            }
            if (rez.Count > 0) return rez.Distinct().ToArray();
            else { rez = new List<string>(1); rez.Add(" - "); }

            return rez.ToArray<string>();
        }
        [WebMethod]
        public string[] GetDeletedUsersStrings(string prefixText, int count)
        {
            prefixText = prefixText.ToLower();
            List<string> rez = new List<string>(count);
            using (var dbs = new DB.DBCotrobaie())
            {
                Func<DB.Useri, bool> fct = (DB.Useri u) => (u.Username + " <" + u.E_mail + "> ").ToLower().Substring(0, prefixText.Length) == prefixText && u.AccountIsValidated && !u.AccountIsSuspended && u.AccountIsTempDeleted;
                var UserMatch = dbs.Useri.Where(fct).Select(o => new { UsernameEmail = o.Username + " <" + o.E_mail + "> " });

                Func<DB.Useri, bool> fct2 = (DB.Useri u) => (u.Username + " <" + u.E_mail + "> ").ToLower().Contains(prefixText) && u.AccountIsValidated && !u.AccountIsSuspended && u.AccountIsTempDeleted;
                var User = dbs.Useri.Where(fct2).Select(o => new { UsernameEmail = o.Username + " <" + o.E_mail + "> " });

                foreach (var u in UserMatch.Concat(User))
                    if (rez.Count < count) rez.Add(u.UsernameEmail);
                    else break;
            }
            if (rez.Count > 0) return rez.Distinct().ToArray();
            else { rez = new List<string>(1); rez.Add(" - "); }

            return rez.ToArray<string>();
        }
        [WebMethod]
        public string[] GetAllUsersStrings(string prefixText, int count)
        {
            prefixText = prefixText.ToLower();
            List<string> rez = new List<string>(count);
            using (var dbs = new DB.DBCotrobaie())
            {
                Func<DB.Useri, bool> fct = (DB.Useri u) => (u.Username + " # " + u.Prenume + " " + u.Nume + " < " + u.E_mail + " > ").ToLower().Substring(0, prefixText.Length) == prefixText.ToLower();
                var UserMatch = dbs.Useri.Where(fct).Select(u => new { UsernameEmail = u.Username + " # " + u.Prenume + " " + u.Nume + " < " + u.E_mail + " > " });

                Func<DB.Useri, bool> fct2 = (DB.Useri u) => (u.Username + " # " + u.Prenume + " " + u.Nume + " < " + u.E_mail + " > ").ToLower().Contains(prefixText.ToLower());
                var User = dbs.Useri.Where(fct2).Select(u => new { UsernameEmail = u.Username + " # " + u.Prenume + " " + u.Nume + " < " + u.E_mail + " > " });

                foreach (var u in UserMatch.Concat(User))
                    if (rez.Count < count) rez.Add(u.UsernameEmail);
                    else break;
            }
            if (rez.Count > 0) return rez.Distinct().ToArray();
            else { rez = new List<string>(1); rez.Add(" - "); }

            return rez.ToArray<string>();
        }
        #endregion

        #region Search dinamic Produse
        [WebMethod]
        public string[] SearchProducts(string prefixText, int count)
        {
            using (var dbs = new DB.DBCotrobaie())
            {
                try
                {
                    if (IsNumber(prefixText))
                    {
                        var word = prefixText;
                        var words = word.Split(new char[] { ';' });

                        if (words.Count() > 1) word = words[words.Count() - 1].Trim();
                        var produse = (from p in dbs.Product
                                       where (p.ISBN != null ? (p.ISBN.StartsWith(word)) : false) || (p.UPC != null ? (p.UPC.StartsWith(word)) : false)
                                       orderby p.name
                                       select new { ID = p.ID, S1 = (p.ISBN != null ? ("ISBN: " + p.ISBN + " ") : ("UPC: " + p.UPC + " ")) + p.name.Substring(0, p.name.Length > 40 ? 40 : p.name.Length) + (p.name.Length > 40 ? "..." : String.Empty), S2 = (p.imageSwatch != null ? p.imageSwatch : "images/no_photo_result.png") })
                                       .Take(count).ToList();
                        if (produse.Count() == 0) return (new List<string>() { "We couldn't find " + prefixText + " in out database" }).ToArray<string>();
                        return produse.Select(x => AjaxControlToolkit.AutoCompleteExtender.CreateAutoCompleteItem(x.S1 + "###" + x.ID.ToString(), x.S2)).ToArray<string>();
                    }
                    else
                    {
                        var word = prefixText.ToLower();
                        var words = word.Split(new char[] { ';' });

                        var vvv = words[words.Count() - 1].Trim();
                        var word2 = " " + vvv;
                        var produse = (from p in dbs.Product
                                       where (p.KeyWords != null ? (p.KeyWords.StartsWith(vvv) || p.KeyWords.Contains(word2)) : false)
                                       orderby p.name
                                       select new { ID = p.ID, S1 = p.name.Substring(0, p.name.Length > 40 ? 40 : p.name.Length) + (p.name.Length > 40 ? "..." : String.Empty), S2 = (p.imageSwatch != null ? p.imageSwatch : "images/no_photo_result.png") })
                                       .Take(count).ToList();
                        if (produse.Count() == 0)
                            produse = (from p in dbs.Product
                                       where p.name.StartsWith(vvv) || p.name.Contains(word2) || (p.authors != null ? (p.authors.StartsWith(vvv) || p.authors.Contains(word2)) : false)
                                       orderby p.name
                                       select new { ID = p.ID, S1 = p.name.Substring(0, p.name.Length > 40 ? 40 : p.name.Length) + (p.name.Length > 40 ? "..." : String.Empty), S2 = (p.imageSwatch != null ? p.imageSwatch : "images/no_photo_result.png") })
                                       .Take(count).ToList();
                        if (produse.Count() == 0) return (new List<string>() { "We couldn't find " + prefixText + " in out database" }).ToArray<string>();
                        return produse.Select(x => AjaxControlToolkit.AutoCompleteExtender.CreateAutoCompleteItem(x.S1 + "###" + x.ID.ToString(), x.S2)).ToArray<string>();
                    }
                }
                catch { return (new List<string>() { "There was a problem with our database. Please try again" }).ToArray<string>(); }
            }
        }
        #endregion

        public bool IsNumber(string word)
        {
            if (word.Length > 13) return false;
            foreach (var v in word)
                if (v < '0' || v > '9') return false;
            return true;
        }
    }
}
